//Original source: http://www.codeproject.com/KB/aspnet/validation_engine.aspx
using System;
using System.Reflection;
using Jaws.Core.Web.Entities.Validation.CustomAttributes;
using Jaws.Core.Web.Entities.Validation.Entities;

namespace Jaws.Core.Web.Entities.Validation
{
    public static class ValidationEngine
    {
        // Validates the entity
        public static bool IsValid<TYPE>(this TYPE item)
        {
            PropertyInfo[] properties = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo property in properties)
            {
                object[] customAtt = property.GetCustomAttributes(typeof (ValidationAttribute), true);

                foreach (object att in customAtt)
                {
                    var valAtt = att as ValidationAttribute;
                    if (valAtt == null) continue;

                    if (valAtt.IsValid(property.GetValue(item, null))) continue;

                    var brokenRule = new BrokenRule
                                         {
                                             Message = String.Format("{0}:{1}", property.Name, valAtt.Message),
                                             PropertyName = property.Name
                                         };
                    if (item is IValidation)
                        ((IValidation) item).BrokenRules.Add(brokenRule);
                }
            }

            return (((IValidation) item).BrokenRules.Count == 0);
        }
    }
}